package com.kfm.controller;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.UUID;

/**
 * author:hlc
 * date:2023/10/19
 *
 * @author 17930
 */
public class TCPServer {
   public static void synFile() {
      Properties properties = new Properties();
      String servertPort = "", basePath="", file="",host="";
      try {
         //加载配置文件
         InputStream inputStream = TCPServer.class.getClassLoader().getResourceAsStream("server.properties");
         properties.load(inputStream);
         servertPort = properties.getProperty("servertPort");
         basePath = properties.getProperty("basePath");
         file = properties.getProperty("file");
         host = properties.getProperty("host");
      } catch (IOException e) {
         System.out.println("加载配置文件失败");
         e.printStackTrace();
      }
      try (ServerSocket sever = new ServerSocket(Integer.parseInt(servertPort));
      ) {
         File file1 = new File(basePath,file);
         System.out.println("等待客户端连接");
         while (true) {
            UUID uuid = UUID.randomUUID();
            String string = uuid.toString();
            Socket accept = null;
            try {
               accept = sever.accept();

               System.out.println("客户端连接成功");
               BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());

               byte[] bytes = bis.readAllBytes();
               String s = new String(bytes);
               String name = "";
               String sufix = "";
               int k = 0;
               out:
               for (int i = 0; i < s.length(); i++) {
                  if ('.' == s.charAt(i)) {
                     while (k < 3) {
                        sufix = sufix + s.charAt(i + 1);
                        k++;
                        i++;
                     }
                     break out;
                  }
                  name = name + s.charAt(i);
               }
              /* System.out.println(name);//文件名称
               System.out.println(sufix);//文件后缀*/
               String dian = ".";
               sufix = dian+sufix;
               BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file1+File.separator + name + sufix));
               bos.write(bytes);
               accept.shutdownInput();
               System.out.println("给客户端一个提示");
               OutputStream outputStream = accept.getOutputStream();
               outputStream.write("文件传输成功".getBytes());
               outputStream.close();
               bos.close();
               bis.close();
            } catch (IOException e) {
               throw new RuntimeException(e);
            }
         }

      } catch (
              IOException e) {
         throw new RuntimeException(e);
      }
   }
}
